<template>
  <div class="order-container">
    <!-- 订单列表 -->
    <el-table :data="orderList" border style="width: 100%">
      <el-table-column prop="orderId" label="订单编号" width="210px" />
      <el-table-column prop="name" label="订单客户" width="90px" />
      <el-table-column prop="address" label="收货地址" width="190px" />
      <el-table-column prop="totalPrice" label="总金额" width="90px" />
      <el-table-column prop="statusName" label="订单状态" width="120px" />
      <el-table-column prop="createTime" label="下单时间" width="200px" />

      <!-- 操作列 -->
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <!-- 仅当状态为 6（待审核）时显示按钮 -->
          <template v-if="scope.row.status === 6">
            <el-button
                type="success"
                size="small"
                @click="handleApprove(scope.row)"
                :loading="scope.row.approving"
                :disabled="scope.row.rejecting"
            >
              同意退货
            </el-button>

<!--            <el-button
                type="danger"
                size="small"
                @click="handleReject(scope.row)"
                :loading="scope.row.rejecting"
                :disabled="scope.row.approving"
            >
              拒绝退货
            </el-button>-->
          </template>

          <!-- 已处理状态提示 -->
          <span v-else-if="scope.row.status === 7" style="color: green">已同意退货</span>
          <span v-else-if="scope.row.status === -1" style="color: red">已拒绝退货</span>
          <span v-else>--</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container" style="margin-top: 20px; text-align: center">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[3, 5, 8, 10]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      />
    </div>
  </div>
</template>

<script>
import { findSearchOrdersReturn, orderReturn } from "../api/orderApi.js";
import { ElMessage, ElMessageBox } from "element-plus";

export default {
  name: "ReturnOrderAudit",
  data() {
    return {
      // 不传任何 status 参数，依赖后端默认查 status=6 和 status=7
      searchForm: {},

      // 状态选项
      statusOptions: [
        { value: 6, label: '已申请退货，待审核' },
        { value: 7, label: '退货审核成功' },
        { value: -1, label: '已拒绝退货' }
      ],

      // 表格数据
      orderList: [],
      currentPage: 1,
      pageSize: 3,
      total: 0,
    };
  },
  created() {
    this.searchOrders();
  },
  methods: {
    /**
     * 搜索订单（带分页）
     */
    async searchOrders() {
      const searchParams = {
        pageNum: this.currentPage,
        pageSize: this.pageSize
        // 不传 status，使用后端默认逻辑
      };

      try {
        const { data } = await findSearchOrdersReturn(searchParams);

        if (data.code === 200) {
          const pageInfo = data.data;

          // 初始化订单列表，并添加响应式字段
          this.orderList = (pageInfo.list || []).map(order => {
            const statusItem = this.statusOptions.find(item => item.value === order.status);
            return {
              ...order,
              // 初始化 loading 状态（即使后续不使用也确保字段存在）
              approving: false,
              rejecting: false,
              // 添加状态名称
              statusName: statusItem ? statusItem.label : '未知状态'
            };
          });

          this.total = pageInfo.total || 0;
        } else {
          ElMessage.error(data.msg || '获取订单列表失败');
          this.orderList = [];
          this.total = 0;
        }
      } catch (err) {
        console.error('搜索订单失败', err);
        ElMessage.error('网络请求失败');
        this.orderList = [];
        this.total = 0;
      }
    },

    /**
     * 分页大小改变
     */
    handleSizeChange(newPageSize) {
      this.pageSize = newPageSize;
      this.currentPage = 1;
      this.searchOrders();
    },

    /**
     * 当前页改变
     */
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.searchOrders();
    },

    /**
     * 同意退货
     */
    async handleApprove(row) {
      try {
        await ElMessageBox.confirm('确定要同意此订单的退货申请吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
      } catch {
        return; // 用户取消
      }

      // 直接赋值（approving 字段已存在，响应式有效）
      row.approving = true;

      try {
        const { data } = await orderReturn({
          orderId: row.orderId,
          status: 7
        });

        if (data.code === 200) {
          ElMessage.success('已同意退货');
          this.searchOrders(); // 刷新列表
        } else {
          ElMessage.warning(data.msg || '操作失败');
        }
      } catch (err) {
        console.error('同意退货失败', err);
        ElMessage.error('网络错误，请重试');
      } finally {
        row.approving = false; // 恢复状态
      }
    },

    /**
     * 拒绝退货
     */
    async handleReject(row) {
      try {
        await ElMessageBox.confirm('确定要拒绝此订单的退货申请吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
      } catch {
        return; // 用户取消
      }

      row.rejecting = true;

      try {
        const { data } = await orderReturn({
          orderId: row.orderId,
          status: -1
        });

        if (data.code === 200) {
          ElMessage.success('已拒绝退货');
          this.searchOrders(); // 刷新列表
        } else {
          ElMessage.warning(data.msg || '操作失败');
        }
      } catch (err) {
        console.error('拒绝退货失败', err);
        ElMessage.error('网络错误，请重试');
      } finally {
        row.rejecting = false;
      }
    }
  }
};
</script>

<style scoped>
.order-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-button + .el-button {
  margin-left: 8px;
}
</style>